package com.freemyleft.left.zapp.selectimage.adapter;


import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class ZhyCommonAdapter<T> extends BaseAdapter {
    protected LayoutInflater mInflater;
    protected Context mContext;
    protected List<T> mDatas;
    protected final int mItemLayoutId;
    private boolean mIsSingleRefresh = false;//是否开启单行刷新（开启每个item需要创建一个ViewHolder）
    private Map<Integer, ZhyViewHolderBean> mViewHolderMap = new HashMap<>();
    public void cleanList() {
        mDatas.clear();
    }

    public ZhyCommonAdapter(Context context, List<T> mDatas, int itemLayoutId) {
        this(context,mDatas,itemLayoutId, false );
    }

    public ZhyCommonAdapter(Context context, List<T> mDatas, int itemLayoutId, boolean isSingleRefresh) {
        mIsSingleRefresh = isSingleRefresh;
        this.mContext = context;
        try {
            this.mInflater = LayoutInflater.from(mContext);
        } catch (Exception e) {
            Log.e("ZhyCommonAdapter","当前contxt已被销毁 ");
        }
        this.mDatas = mDatas;
        this.mItemLayoutId = itemLayoutId;
    }


    @Override
    public int getCount() {
        // return mDatas.size();
        return mDatas.size();
    }

    @Override
    public T getItem(int position) {
        // return mDatas.get(position);
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void notifyDataSetChangedAll(){
        for ( int i = 0; i < mDatas.size(); i++){
            notifyDataSetChanged(i);
        }
    }

    public void notifyDataSetChanged(int position){
        if (!mIsSingleRefresh){
            throw new RuntimeException("请在构造方法中先设置开启单行刷新");
        }
        convert(mViewHolderMap.get(position).getViewHolder(), getItem(mViewHolderMap.get(position).getPosition()), mViewHolderMap.get(position).getPosition());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(mItemLayoutId, parent, false);
            convertView.setTag(new ZhyViewHolder(convertView));
        }
        ZhyViewHolder viewHolder = (ZhyViewHolder) convertView.getTag();
        if ( mIsSingleRefresh){
            mViewHolderMap.put(position, new ZhyViewHolderBean(viewHolder, position));
        }
        convert(viewHolder, getItem(position), position);
        return convertView;
    }

    public abstract void convert(ZhyViewHolder holder, T item, int position);
}
